package com.ruoyi.web.controller.test;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.socket.config.BinanceWebSocketConfig;
import com.ruoyi.socket.manager.BinanceConnectionManager;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 币安WebSocket测试控制器
 */
@RestController
@RequestMapping("/test/binance")
public class BinanceWebSocketTestController {

    @Resource
    private BinanceConnectionManager binanceConnectionManager;
    
    @Resource
    private BinanceWebSocketConfig binanceWebSocketConfig;

    /**
     * 获取当前连接状态
     */
    @GetMapping("/status")
    public AjaxResult getConnectionStatus() {
        String statusInfo = binanceConnectionManager.getConnectionStatusInfo();
        return AjaxResult.success("连接状态信息", statusInfo);
    }

    /**
     * 切换到下一个地址
     */
    @GetMapping("/switch")
    public AjaxResult switchUrl() {
        String oldUrl = binanceWebSocketConfig.getCurrentUrl();
        boolean switched = binanceConnectionManager.switchToNextUrl();
        String newUrl = binanceWebSocketConfig.getCurrentUrl();
        
        return AjaxResult.success("地址切换" + (switched ? "成功" : "失败"), 
                String.format("从 %s 切换到 %s", oldUrl, newUrl));
    }

    /**
     * 重置连接状态
     */
    @GetMapping("/reset")
    public AjaxResult resetConnection() {
        binanceConnectionManager.resetConnectionStatus();
        return AjaxResult.success("连接状态已重置");
    }

    /**
     * 获取所有配置的地址
     */
    @GetMapping("/urls")
    public AjaxResult getAllUrls() {
        return AjaxResult.success("所有WebSocket地址", binanceWebSocketConfig.getUrls());
    }

    /**
     * 测试连接失败处理
     */
    @GetMapping("/test-failure")
    public AjaxResult testFailureHandling() {
        boolean shouldSwitch = binanceConnectionManager.handleConnectionFailure("Test failure: HTTP 451");
        return AjaxResult.success("失败处理测试", 
                shouldSwitch ? "触发了地址切换" : "未触发地址切换");
    }

    /**
     * 获取当前WebSocket URL
     */
    @GetMapping("/current-url")
    public AjaxResult getCurrentUrl() {
        String klineUrl = binanceConnectionManager.getCurrentWebSocketUrl("/ws/btcusdt@kline_1m");
        String tickerUrl = binanceConnectionManager.getCurrentWebSocketUrl("/ws/!ticker@arr");
        
        return AjaxResult.success("当前WebSocket URLs", 
                String.format("K线: %s\nTicker: %s", klineUrl, tickerUrl));
    }
} 